layui.extend({
    common_api:'{/}/static/util/common_api'
}).define(['upload','jquery','element','laytpl','common_api'],function (exports) {
    var upload = layui.upload,
        $ = jquery = layui.jquery,
        element = layui.element,
        laytpl = layui.laytpl,
        common_api = layui.common_api;
    var upload_api = {
        upload_data:function (id_ext) {
            id_ext = arguments[0] ? arguments[0] : null;
            var upload_obj = id_ext ? $("#upload_"+id_ext) : $(".upload_api");
            var upload_btn = upload_obj.eq(upload_obj.length - 1);
            var data = {};
            data.url = upload_btn.data('url');
            data.check = upload_btn.data('check');
            data.idExt = upload_btn.data('idExt');
            data.accept = upload_btn.data('accept') || 'images';
            data.acceptMime = upload_btn.data('acceptMime') || '';
            data.exts = upload_btn.data('exts') || '';
            data.field = upload_btn.data('field') || 'image';
            data.multiple = upload_btn.data('multiple') || false;
            return data;
        }
        ,render:function (id_ext) {
            //多图片上传
            var data = upload_api.upload_data(id_ext);
            console.log(data);
            upload.render({
                elem: '#upload_'+data.idExt
                ,url: data.url
                ,multiple: data.multiple
                ,auto:false
                ,accept:data.accept
                ,acceptMime: data.acceptMime
                ,exts:data.exts
                ,field:data.field
                ,choose: function(obj){
                    //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                    obj.preview(function(index, file, result){
                        common_api.dynamicLoadJs('https://cdnjs.cloudflare.com/ajax/libs/spark-md5/3.0.0/spark-md5.min.js',function () {
                            var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
                                chunkSize = 2097152, // 每次读取2MB
                                chunks = Math.ceil(file.size / chunkSize),
                                currentChunk = 0,
                                spark = new SparkMD5.ArrayBuffer(),
                                frOnload = function(e){
                                    spark.append(e.target.result);
                                    currentChunk++;
                                    if (currentChunk < chunks) {
                                        loadNext();
                                    }else{
                                        var md5 = spark.end();
                                        $.post(data.check,{md5:md5})
                                            .success(function (res) {
                                                if(!res.code){
                                                    uploadSuccess(res);
                                                }else{
                                                    obj.upload(index,file);
                                                }
                                            })
                                            .error(function () {
                                                obj.upload(index,file);
                                            });
                                    }
                                },
                                frOnerror = function () {
                                    obj.upload(index,file);
                                };
                            function loadNext() {
                                var fileReader = new FileReader();
                                fileReader.onload = frOnload;
                                fileReader.onerror = frOnerror;
                                var start = currentChunk * chunkSize,
                                    end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
                                fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
                            }
                            loadNext();
                        });
                    });
                }
                ,before: function(obj){
                    $("#progress_"+data.idExt).removeClass('layui-hide');
                }
                ,progress: function(n){
                    var percent = n + '%'; //获取进度百分比
                    element.progress('progress_'+data.idExt, percent);
                }
                ,done: function(res){
                    $("#progress_"+data.idExt).addClass('layui-hide');
                    //上传完毕
                    if(res.code){
                        uploadSuccess(res);
                    }else{
                        uploadFail(res);
                    }
                }
                ,error:function (index,upload) {
                    uploadError();
                }
            });

            function uploadSuccess(res) {
                notice.success(res.msg);
                var tpl = $("#tpl_"+data.idExt).html();
                laytpl(tpl).render(res,function (html) {
                    if(data.multiple) {
                        $('#preview_' + data.idExt).append(html);
                    }else{
                        $('#preview_' + data.idExt).html(html);
                    }
                });
                var ipt =  $("#upload_input_"+data.idExt);
                if(data.multiple) {
                    var path = ipt.val();
                    if (path) {
                        path += ',';
                    }
                    ipt.val(path + res.data.path);
                }else{
                    ipt.val(res.data.path);
                }
            }

            function uploadFail(res) {
                notice.error(res.msg);
            }
            function uploadError() {
                $("#progress_"+data.idExt).addClass('layui-hide');
            }
        }
    };
    exports('upload_api',upload_api);
});